package com.h3bpm.kumhosunny.merits.controller;

import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import OThinker.H3.Entity.Notification.IDingTalkAdapter;
import OThinker.H3.Entity.Notification.Notification;
import OThinker.H3.Portal.webservices.BPMService;
import OThinker.H3.Portal.webservices.Entity.BPMServiceResult;
import OThinker.H3.Portal.webservices.Entity.DataItemParam;
import OThinker.H3.Portal.webservices.impl.BPMServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.h3bpm.kumhosunny.common.utils.SqlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/Portal/MyMeritsController")
public class MyMeritsManagerController extends ControllerBase {

    @Override
    public String getFunctionCode() {
        return null;
    }

    public static final Logger LOGGER= (Logger) LoggerFactory.getLogger(MyMeritsManagerController.class);

    private BPMService bpmService = new BPMServiceImpl();

    private ObjectMapper objectMapper = new ObjectMapper();

    IDingTalkAdapter iDingTalkAdapter=getEngine().getDingTalkAdapter();   //钉钉适配器

    //http://localhost:8081/Portal/MyMeritsController/startMyMeritsSonProcess?instanceId=e9baa287-ee88-453f-af86-10fbc7cc5c86

    @RequestMapping("/startMyMeritsSonProcess")
    @ResponseBody
    public String startMyMeritsSonProcess(String instanceId){

        String result="200";

        try {

            InstanceData instanceData=new InstanceData(getEngine(),instanceId, User.AdministratorID);

            //数据封装
            HashMap<String, Object> valueTable = instanceData.getBizObject().getValueTable();

            Map<String,List> resultMaps=this.myMeritsProcessiongData(instanceId,valueTable);

            for(String nowUser:resultMaps.keySet()){
                //当前用户—子流程发起人
                User user= (User) getEngine().getOrganization().GetUnit(nowUser);
                LOGGER.info("> MeritsSon: 发起子流程 >发起人:" + user.getCode());
                BPMServiceResult bpmServiceResult = bpmService.StartWorkflow("H3", "Authine", "OKRevalueAT", user.getCode(), false, resultMaps.get(nowUser));

                //等待1秒
                Thread.sleep(500);
                String workItemId = SqlUtil.doQuery(String.format("select  objectid from OT_workitem where instanceId = '%s' and ActivityCode = 'Activity2' and Participant = '%s' limit 1",bpmServiceResult.getInstanceId(),user.getObjectID())).getRows().get(0).getString(0);

                String pc_url="http://www.kumhosunny.cn:8099/Portal/template/ddhome.html?loginfrom=dingtalk&WorkItemID="+workItemId+"&time="+System.currentTimeMillis();
                String mobile_url="http://www.kumhosunny.cn:8099/Mobile/#/dingtalkmsg/"+workItemId+"?time="+System.currentTimeMillis();

                //发送消息通知用户
                //子流程数据
                InstanceData sonData=new InstanceData(getEngine(),bpmServiceResult.getInstanceId(),User.AdministratorID);

                Notification notification=new Notification(OThinker.H3.Entity.Notification.NotifyType.DingTalk,null,user.getObjectID(),
                        user.getDingTalkAccount(),null,0,bpmServiceResult.getInstanceId(),
                        ""+sonData.getInstanceContext().getInstanceName(),"您有一条流程待办,点击查看",null,mobile_url,pc_url,null);

                getEngine().getNotifier().Notify(notification);

                LOGGER.info("> " + objectMapper.writeValueAsString(bpmServiceResult));
            }

        } catch (Exception e) {
            result="500";
            e.printStackTrace();

        }

        return result;

    }


    /***
     * 数据处理返回
     * @param instanceId
     * @param valueTable
     * @return
     * @throws Exception
     */
    public Map<String, List> myMeritsProcessiongData(String instanceId, HashMap<String, Object> valueTable) throws Exception {
        Map<String,List> resultMaps=new HashMap<>();

        //获取子表数据遍历发起人
        BizObject[] meritsSonTables= (BizObject[]) valueTable.get("evaluateChart1");

        //获取团队分类
        String groupTypeStr= (String) valueTable.get("classify1");
        //获取业务绩效
        String groupNameStr= (String) valueTable.get("PositionAndBusiness1");

        //遍历子表数据
        if(meritsSonTables.length!=0 && null!=meritsSonTables){

            for(int i=0;i<meritsSonTables.length;i++){
                //数据映射
                List<DataItemParam> dataParam = new ArrayList<>();

                HashMap<String, Object> objectHashMap = meritsSonTables[i].getValueTable();

                //获取当前子表评估人
                String evaluatorPerson= (String) objectHashMap.get("Assessors");
                dataParam.add(new DataItemParam("parentInstanceId",instanceId)); //父流程ID
                dataParam.add(new DataItemParam("personal",valueTable.get("reporter1")));  //被评估人
                dataParam.add(new DataItemParam("performanceOfCycle",valueTable.get("peformanceOfCycle1")));
                dataParam.add(new DataItemParam("classify",groupTypeStr));
                dataParam.add(new DataItemParam("positionAndBusiness",groupNameStr));
                dataParam.add(new DataItemParam("Assessors",evaluatorPerson));

                //日期
                dataParam.add(new DataItemParam("reportDate",valueTable.get("reportDate")));


                //放入resultMap
                resultMaps.put(evaluatorPerson,dataParam);

            }


        }


        return resultMaps;

    }



    /***
     * 子流程提交数据，返回父表
     * @param instanceId
     * @return
     */
    //http://localhost:8081/Portal/MyMeritsController/sonMeritsSubmit?instanceId=96b26bdb-4025-46f7-a91b-6ebc22a2815b
    @RequestMapping("/sonMeritsSubmit")
    @ResponseBody
    public String sonMeritsSubmit(String instanceId){
        String result="200";

        try {
            //获取当前子流程数据
            InstanceData instanceData=new InstanceData(getEngine(),instanceId, User.AdministratorID);

            //获取数据
            HashMap<String, Object> valueTable = instanceData.getBizObject().getValueTable();

            //当前子流程发起人ID
            String submitFormUserId= (String) valueTable.get("Assessors");

            //绩效等级
            String performanceRate= (String) valueTable.get("performanceRate");

            //绩效系数
            String coefficient= (String) valueTable.get("coefficient");

            //OKR(业务策略制定的深度思考)
            String okr= (String) valueTable.get("OKR");

            //业绩达成
            String KPIresults= (String) valueTable.get("KPIresults");

            //团队建设、文化与氛围
            String teamBuilding= (String) valueTable.get("teamBuilding");

            //个人学习
            String learning= (String) valueTable.get("personalLearning");

            //获取父表数据
            InstanceData parentData=new InstanceData(getEngine(), (String) valueTable.get("parentInstanceId"),User.AdministratorID);

            //封装父表数据
            HashMap<String, Object> parentValueTable = parentData.getBizObject().getValueTable();
            //获取父表下的子表数据
            BizObject[] parentSonTableValue= (BizObject[]) parentValueTable.get("evaluateChart1");

            //遍历赋值
            for(BizObject bizObject:parentSonTableValue){
                HashMap<String, Object> objectHashMap=bizObject.getValueTable();

                //确定当前账户
                if(objectHashMap.get("Assessors").equals(submitFormUserId)){
                    //父表赋值
                    bizObject.setItem("performanceRate",performanceRate);  //绩效等级
                    bizObject.setItem("coefficient",coefficient);  //绩效系数
                    bizObject.setItem("OKR",okr); //OKR
                    bizObject.setItem("KPIresults",KPIresults);   //业绩达成
                    bizObject.setItem("teamBuilding",teamBuilding);  //团队建设
                    bizObject.setItem("learning",learning);  //个人学习与成长
                    LOGGER.info("> MeritsSon: 子流程数据返回父表,子流程ID:"+instanceId);
                    break;
                }

            }
            //数据先录入后计算

            //遍历判断当前汇总状态
            Integer successPerson=0;
            for(BizObject bizObject:parentSonTableValue){
                HashMap<String, Object> objectHashMap=bizObject.getValueTable();
                //计算已完成人
                if(null!=objectHashMap.get("performanceRate") && !"".equals(objectHashMap.get("performanceRate"))){
                    successPerson++;  //已完成汇总人数+1
                }
            }

            //遍历完成判断 && 提交过来已完成人数+1
            if(successPerson!=parentSonTableValue.length){
                Integer noperson=(parentSonTableValue.length-successPerson);
                parentData.getBizObject().setItem("evaluateChartState","未完成人数:"+noperson);
            }else{
                parentData.getBizObject().setItem("evaluateChartState","已完成");
            }

            //保存父表所有数据
            parentData.Submit();



        } catch (Exception e) {
            result="500";
            e.printStackTrace();
        }

        return result;
    }

}
